//
//  SLSetLockNameVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/16.
//

#import "SLSetLockNameVC.h"
#import "SLSuccessAlertView.h"
#import "SLAddLockSetModelVC.h"
#import "SLSetBridgeWifiVC.h"
@interface SLSetLockNameVC (){
    BOOL _isAddBridge;
}

@end

@implementation SLSetLockNameVC
- (void)viewDidLoad {
    [super viewDidLoad];
    _isAddBridge = _type != 1;
    [self setUpSubViews];
}

-(void)setUpSubViews{
    if (_isAddBridge) {
        self.title = kLocalString(@"Add a new bridge");
        _tipLbl.text = kLocalString(@"Bridge paired! Make a name for this bridge.");
        [_tf setPlaceholderWithPlaceholderText:kLocalString(@"Enter Bridge Name") withColor:KColor_placeholdar withFont:kFont(18)];
    }else{
        self.title = kLocalString(@"Add new device");
        _tipLbl.text = kLocalString(@"Lock paired! Make a name for this lock.");
        [_tf setPlaceholderWithPlaceholderText:kLocalString(@"Enter Lock Name") withColor:KColor_placeholdar withFont:kFont(18)];
    }
    
    _sureBtn.btnStyle = 1;
    [_sureBtn setTitle:kLocalString(@"Done") forState:UIControlStateNormal];
    self.tfBgView.layer.cornerRadius = 20;
    self.tfBgView.layer.masksToBounds = YES;
   
}


- (IBAction)sureAction:(id)sender {
    
    if (_tf.text.length == 0) {
        if (_isAddBridge) {
            kShowToast(@"Enter Bridge Name");
        }else{
            kShowToast(@"Enter Lock Name");
        }
        return;
    }
    //绑定网关
    if (_isAddBridge) {
        //绑定网关
        [ZCTool showLoadingOnKeyWindow];
        [[SLBluetoothManager sharedManager] startSearchDeviceAndConnect:self->_model.deviceNo isBridge:self->_isAddBridge finish:^(BOOL isSuccess, CBPeripheral *peripheral, id data, NSString *errorMsg) {
            if (!isSuccess) {
                kCurDevice = nil;
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(@"Connect faild");
                return;
            }
            kCurDevice = self->_model;
            [self bindBridgeServiceDevice];
        }];
        return;
    }
    
    //网关绑定蓝牙锁
    if (_isBridgeAddLock) {
        NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo,
                                 @"bdAddr":_model.bridgeScanInfo[@"bdAddr"],
                                 @"productID":_model.bridgeScanInfo[@"productID"],
                                 @"license":_model.bridgeScanInfo[@"license"],
                                 @"bdType":@"0",
                                 @"deviceName":self->_tf.text};
        [ZCTool showLoadingOnKeyWindow];
        [ZKHttpManager postWithPath:@"/msl_user/conDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            [self.navigationController popToViewController:self->_bridgeListVc animated:YES];
            if (self.addLockBlock) self.addLockBlock();
            kNotifyRefreshDevcieList;
        }];
        return;
    }
    
    //app绑定蓝牙锁
    [ZCTool showAwakeTipAlert:^{
        [ZCTool showLoadingOnKeyWindow];
        [[SLBluetoothManager sharedManager] startSearchDeviceAndConnect:self->_model.deviceNo isBridge:self->_isAddBridge finish:^(BOOL isSuccess, CBPeripheral *peripheral, id data, NSString *errorMsg) {
            if (!isSuccess) {
                kCurDevice = nil;
                [ZCTool hideLoadingOnKeyWindow];
                kShowToast(@"Connect faild");
                return;
            }
            kCurDevice = self->_model;
            [[SLBluetoothManager sharedManager] getDeviceBaseInfo:^(id data) {
                self->_model.macAddress = data[@"mac"];
                if (self->_model.macAddress.length == 0) {
                    kShowToast(@"Bind device faild");
                    [ZCTool hideLoadingOnKeyWindow];
                    return;
                }
                [self bindLockServiceDevice];
            }];
        }];
    }];
}

//绑定网关设备
-(void)bindBridgeServiceDevice{
    //获取mac
    [[SLBluetoothManager sharedManager] getGateMacAddressWith:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
        if (!isSuccess) {
            [ZCTool hideLoadingOnKeyWindow];
            kShowToast(@"Failed to set name.");
            return;
        }
        NSString *macAdress = data;
        //服务端绑定
        NSDictionary *params = @{@"deviceNo":self->_model.deviceNo,
                                 @"deviceName":self->_tf.text,
                                 @"macAddress":macAdress,
                                 @"model":self->_model.productName};
        [ZKHttpManager postWithPath:@"/msl_user/BindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull serMessage) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                //服务端绑定失败
                kShowToast(serMessage);
                return;
            }
            //添加成功 - 跳转到配网页面
            kNotifyRefreshDevcieList;
            SLSetBridgeWifiVC *vc = [SLSetBridgeWifiVC new];
            vc.model = self->_model;
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }];
}

//服务器绑定
-(void)bindLockServiceDevice{
    //先服务端绑定
    NSDictionary *params = @{@"deviceNo":_model.deviceNo,
                             @"deviceName":_tf.text,
                             @"major":_model.major,
                             @"minor":_model.minor,
                             @"macAddress":_model.macAddress};
    [ZKHttpManager postWithPath:@"/msl_user/BindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull serMessage) {
        if (!isSuccessed) {
            //已经被绑定了
            if ([code isEqualToString:@"601"]) {
                [self unBindOrgDevice:^(BOOL isSuccess) {
                    if (isSuccess) {
                        [self bindDevice:serMessage];
                    }else{
                        //服务端绑定失败
                        [ZCTool hideLoadingOnKeyWindow];
                        kShowToast(serMessage);
                    }
                }];
                return;
            }
            //服务端绑定失败
            [ZCTool hideLoadingOnKeyWindow];
            kShowToast(serMessage);
        }else{
            [self bindDevice:serMessage];
        }
    }];
}

-(void)bindDevice:(NSString *)serMessage{
    //硬件绑定
    [[SLBluetoothManager sharedManager] bindDeviceWith:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccess) {
            kShowToast(@"Bind device faild");
            return;
        }
        kShowToast(serMessage);
        //添加成功
        kNotifyRefreshDevcieList;
        SLAddLockSetModelVC *vc = [SLAddLockSetModelVC new];
        vc.model = self->_model;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

-(void)unBindOrgDevice:(void(^)(BOOL isSuccess))finish{
    NSDictionary *params = @{@"deviceNo":_model.deviceNo};
    [ZKHttpManager postWithPath:@"/msl_user/UnBindDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString    * _Nonnull serMessage) {
        if (finish) {
            finish(isSuccessed);
        }
    }];
}


@end
